package com.xms.queryview.core;

import com.xms.core.model.KeyValuePair;
import com.xms.queryview.core.component.RowCommand;
import com.xms.schema.entity.Attribute;
import com.xms.sdk.core.query.ConditionExpression;
import com.xms.sdk.core.query.LogicalOperator;
import com.xms.sdk.extensions.ConditionExpressionExt;
import com.xms.utils.CollectionUtil;

import java.util.List;

/**
 * <p>
 * RowCommandExtensions
 * </p>
 *
 * @author migo
 * @since 2021/9/3
 */
public class RowCommandExt {

    public static boolean isTrue(RowCommand rowCmd, KeyValuePair<String, Object> data, List<Attribute> attributes)
    {
        boolean rowFlag = false;
        boolean cndFlag = false;
        if (CollectionUtil.notEmpty(rowCmd.Conditions))
        {
            for (ConditionExpression cmdCond : rowCmd.Conditions)
            {
                if (data.containsKey(cmdCond.AttributeName.toLowerCase()))
                {
                    Object value = data.get(cmdCond.AttributeName.toLowerCase());
                    Attribute attr = attributes.stream().filter(n -> n.getName().equals(cmdCond.AttributeName.toLowerCase())).findFirst().get();

                    //符合条件时
                    if (ConditionExpressionExt.isTrue(cmdCond, attr, value))
                    {
                        //或者关系
                        if (rowCmd.LogicalOperator == LogicalOperator.Or)
                        {
                            cndFlag = true;
                            rowFlag = true;
                            break;
                        }
                        else//并且
                        {
                            cndFlag = true;
                            if (rowCmd.Conditions.length == 1)
                            {
                                rowFlag = true;
                                break;
                            }
                        }
                    }
                    else//不符合条件时
                    {
                        //或者关系
                        if (rowCmd.LogicalOperator == LogicalOperator.Or)
                        {
                            cndFlag = false;
                        }
                        else//并且
                        {
                            cndFlag = false;
                            rowFlag = false;
                            break;
                        }
                    }
                }
                if (rowFlag)
                {
                    break;
                }
                else
                {
                    rowFlag = cndFlag;
                }
            }
        }
        return rowFlag;
    }
}
